import * as vscode from 'vscode';
import * as path from 'path';
import { HighlightManager } from './HighlightManager';
import { JsonFormatter } from './JsonFormatter';
import { JsonResultViewer } from './JsonResultViewer';

export interface MessageHandlerOptions {
    highlightManager: HighlightManager;
}

export class MessageHandler {
    private highlightManager: HighlightManager;

    constructor(options: MessageHandlerOptions) {
        this.highlightManager = options.highlightManager;
    }

    public handleMessage(message: any): void {
        if (!message || typeof message !== 'object') {
            console.warn('Received invalid message:', message);
            return;
        }

        switch (message.cmd) {
            case 'open_file':
                this.handleOpenFile(message);
                break;
            case 'error':
                vscode.window.showErrorMessage(message.desc || '未知错误');
                break;
            case 'warn':
                vscode.window.showWarningMessage(message.desc || '未知警告');
                break;
            case 'info':
                vscode.window.showInformationMessage(message.desc || '信息提示');
                break;
            case 'script_result':
                this.handleScriptResult(message);
                break;
            case 'lua_to_json_result':
                this.handleLuaToJsonResult(message);
                break;
            default:
                console.log('Unknown message command:', message.cmd);
        }
    }

    private handleOpenFile(message: any): void {
        const workspaceFolders = vscode.workspace.workspaceFolders;
        if (!workspaceFolders) {
            vscode.window.showErrorMessage('请先打开一个工作区');
            return;
        }

        const rootPath = workspaceFolders[0].uri.fsPath;
        let fullPath = "";
        
        fullPath = path.join(rootPath, message.path || '');

        this.highlightManager.highlightError({
            filePath: fullPath,
            line: message.line || 0,
            column: message.column || 1,
            description: message.desc || "错误信息xxxxxx"
        });
    }

    private handleScriptResult(message: any): void {
        const result = message.result || message.desc || 'JS执行结果';
        
        // 检查是否为JSON格式
        if (typeof result === 'string' && JsonFormatter.isValidJson(result)) {
            JsonResultViewer.showJsonResult(result, 'JS执行结果');
        } else {
            vscode.window.showInformationMessage(result);
        }
    }

    private handleLuaToJsonResult(message: any): void {
        const result = message.result || message.data || message.desc || 'Lua执行结果';
        
        // 检查是否为JSON格式
        if (typeof result === 'string' && JsonFormatter.isValidJson(result)) {
            JsonResultViewer.showJsonResult(result, 'Lua执行结果');
        } else if (typeof result === 'object') {
            // 如果是对象，直接格式化为JSON
            JsonResultViewer.showJsonResult(JSON.stringify(result, null, 2), 'Lua执行结果');
        } else {
            // 普通文本结果
            JsonResultViewer.showTextResult(String(result), 'Lua执行结果');
        }
    }
}
